<?php

namespace app\app\controller;

use think\Db;

class Cart extends Common
{
    //获取购物车列表
    public function get_list()
    {
        $uid = token_decode(req('token'));
        $seller_id = req('seller_id');
        $msg['state'] = 0;
        $msg['data'] = null;
        if (empty($uid) || empty($seller_id)) {
            $msg['msg'] = '参数错误';
        } else {
            $msg['state'] = 1;
            $goods_array = Db::table('cart')->where(['uid' => $uid, 'seller_id' => $seller_id, 'order_id' => ''])->select();
            $price = 0;
            $goods_number = 0;
            foreach ($goods_array as $k => $v) {
                $goods = Db::table('service')->where('id', $v['goods_id'])->find();
                unset($goods_array[$k]['uid']);
                unset($goods_array[$k]['seller_id']);
                unset($goods_array[$k]['order_id']);
                $goods_array[$k]['title'] = (string)$goods['title'];
                $goods_array[$k]['image'] = (string)$goods['image1'];
                $goods_array[$k]['service'] = (string)$goods['service'];
				if($v['spec']){
					$spec = Db::table('service_spec')->where(['service_id' => $v['goods_id'],'id' => $v['spec']])->find();
					if($spec){
						$goods['price'] = $spec['price'];
						$goods_array[$k]['title'] = (string)($goods['title'].'['.$spec['title'].']');
					}
				}
                if(!empty((float)$goods['discount'])){
                    $goods['price'] = (string)($goods['price']*($goods['discount']/10));
                }
                $goods_array[$k]['price'] = (string)$goods['price'];
                $price += $goods['price'] * $v['number'];
                $goods_number += $v['number'];
            }
            $data['goods'] = $goods_array;
            $data['goods_number'] = $goods_number;
            $data['price'] = (string)$price;
            $msg['data'] = $data;
            $msg['msg'] = '获取成功';
        }
        return json($msg);
    }

    //编辑购物车
    public function edit()
    {
        $uid = token_decode(req('token'));
        $seller_id = req('seller_id');
        $goods_id = req('goods_id');
        $number = req('number');
        $spec = req('spec');
        $instore = req('instore');
				$instore = $instore?$instore:1;
				$spec = $spec?$spec:0;
        $msg['state'] = 0;
        $msg['data'] = '';
        if (empty($uid) || empty($goods_id) || empty($seller_id) || $number == '') {
            $msg['msg'] = '参数错误';
        } else {
            $msg['state'] = 1;
            $check = Db::table('cart')->where(['uid' => $uid, 'seller_id' => $seller_id, 'goods_id' => $goods_id,'order_id'=>'','spec'=>$spec,'instore'=>$instore])->count();
            if ($check > 0) {
                if ($number <= 0) {
                    $msg['msg'] = '删除成功';
                    Db::table('cart')->where(['goods_id' => $goods_id, 'seller_id' => $seller_id, 'uid' => $uid,'order_id'=>'','spec'=>$spec,'instore'=>$instore])->delete();
                } else {
                    $msg['msg'] = '加入购物车成功';
                    Db::table('cart')->where(['goods_id' => $goods_id, 'seller_id' => $seller_id, 'uid' => $uid,'order_id'=>'','spec'=>$spec,'instore'=>$instore])->update(['number' => $number]);
                }
            } else {
                if ($number != 0) {
                    $msg['msg'] = '加入购物车成功';
                    $data['uid'] = $uid;
                    $data['seller_id'] = $seller_id;
                    $data['goods_id'] = $goods_id;
                    $data['number'] = $number;
                    $data['spec'] = $spec;
                    $data['instore'] = $instore;
                    Db::table('cart')->insert($data);
                } else {
                    $msg['msg'] = '删除成功';
                    Db::table('cart')->where(['goods_id' => $goods_id, 'seller_id' => $seller_id, 'uid' => $uid,'order_id'=>''])->delete();
                }
            }
            $msg['state'] = 1;
        }
        return json($msg);
    }

    //获取下单结算页面详情数据
    public function order_count()
    {
        $uid = token_decode(req('token'));
        $seller_id = req('seller_id');
        $address_id = req('address_id');
        $red_id = req('red_id');
        $instore = req('instore');
				$instore = $instore?$instore:1;
        $pay = req('pay');
        $remark = req('remark');
        $msg['state'] = 0;
        $msg['data'] = null;
        $data = [];
        if (empty($uid) || empty($seller_id)) {
            $msg['msg'] = '参数错误';
        } else {
            $seller = Db::table('seller')->where('id', $seller_id)->find();
            //商品
            $goods_array = Db::table('cart')->field('seller_id,goods_id,number,spec')->where(['uid' => $uid, 'seller_id' => $seller_id,'order_id'=>'','instore'=>$instore])->select();
            if (count($goods_array) == 0) {
                $msg['msg'] = '请选购商品后在下单';
            } else {
                $msg['state'] = 1;
                $msg['msg'] = '获取成功';
                $goods_total = 0;
                $goods_price = 0;
                $box_charge = 0;
                $isMoney_off = true;
                $fields = 'id as goods_id,discount,title,image1 as image,service,price,box_charge';
                foreach ($goods_array as $k => $v) {
                    $goods = Db::table('service')->field($fields)->where('id', $v['goods_id'])->find();
                    $goods['number'] = $v['number'];
                    $goods_total += $v['number'];
					if($v['spec']){
						$spec = Db::table('service_spec')->where(['service_id' => $v['goods_id'],'id' => $v['spec']])->find();
						if($spec){
							$goods['price'] = $spec['price'];
							$goods['title'] = (string)($goods['title'].'['.$spec['title'].']');
						}
					}
                    if(!empty((float)$goods['discount'])){
                        $isMoney_off = false;
                        $goods['price'] = (string)($goods['price']*($goods['discount']/10));
                    }
                    $goods_price += $v['number'] * $goods['price'];
                    $box_charge += $v['number'] * $goods['box_charge'];
                    $goods_array[$k] = $goods;
                }
                $data['goods'] = $goods_array;

                //各种费
                $data['goods_total'] = (string)$goods_total;
                $data['goods_price'] = (string)$goods_price;
                $data['box_charge'] = (string)$box_charge;

                //默认地址
                if (empty($address_id)) {
                    $data['address_obj'] = Db::table('address')->field('id as address_id,label,phone,name,address_title,address_content,address_detail,sex,lng,lat')->where(['uid' => $uid, 'def' => 1])->find();
                } else {
                    $data['address_obj'] = Db::table('address')->field('id as address_id,label,phone,name,address_title,address_content,address_detail,sex,lng,lat')->where(['uid' => $uid, 'id' => $address_id])->find();
                }
                $express_charge_info = Db::table('express_config')->where('aid', $seller['aid'])->find();
                if($data['address_obj']){
                    $lng = $data['address_obj']['lng'];
                    $lat = $data['address_obj']['lat'];
                    $pi = ($this->getDistance($lat, $lng, $seller['lat'], $seller['lng'])) / 1000;
                    /*if ($pi > 10) {
                        $msg['state'] = 0;
                        $msg['msg'] = '超出配送范围';
                    }*/
                    $express_charge = $express_charge_info['charge'];
                    if($pi > $express_charge_info['scope']){
                        $express_charge += $express_charge_info['add_charge']*($pi-$express_charge_info['scope']);
                    }
                    if ($express_charge < $express_charge_info['charge']) {
                        $express_charge = $express_charge_info['charge'];
                    }
                    $data['express_charge'] = (string)round($express_charge);
                }else{
                    $msg['state'] = 0;
                    $msg['msg'] = '请选择地址';
                    // $data['express_charge'] = (string)$express_charge_info;
                    $data['express_charge'] = '0';
                }
                $data['sum_price'] = (string)($goods_price+$box_charge+$data['express_charge']);

                if($seller['business'] == 0){
                    $msg['state'] = 0;
                    $msg['msg'] = '商家休息中，无法接单';
                    if($seller['advance'] == 1){
                        $msg['state'] = 1;
                        $msg['msg'] = '商家休息中，支持预定，';
                    }
                }

                if($data['sum_price'] < $seller['min_express_charge']){
                    $msg['state'] = 0;
                    $msg['msg'] = '低于最低起送价';
                }

                $isDis_price = $goods_price+$box_charge+$data['express_charge'];
                //是否首单
                if (!empty($seller['new_user_reduction'])) {
                    $count = Db::table('order')->where(['uid' => $uid, 'status' => ['between', '2,5']])->count();
                    if ($count == 0) {
                        $data['new_user_reduction'] = $seller['new_user_reduction'];
                    } else {
                        $data['new_user_reduction'] = '';
                    }
                } else {
                    $data['new_user_reduction'] = '';
                }
                $isDis_price -= $data['new_user_reduction'];

                $system_minus = '';
                $seller_minus = '';
                //店铺满减
                $money_off = Db::table('money_off')->where(['seller_id' => $seller_id])->where('full<'.$isDis_price)->order('full desc')->find();
                if (count($money_off) > 0 && $isMoney_off == true) {
                    $data['money_off_text'] = '满' . $money_off['full'] . '减' . $money_off['minus'];
                    $data['money_off'] = $money_off['minus'];
                    $system_minus = $money_off['system_minus'];
                    $seller_minus = $money_off['seller_minus'];
                } else {
                    $data['money_off_text'] = '';
                    $data['money_off'] = '';
                }
                $isDis_price -= $data['money_off'];

                //优惠券
                if (empty($red_id)) {
                    $data['red_packet'] = '';
                } else {
                    $red_packet_info = Db::table('red_packet')->where(['uid' => $uid, 'id' => $red_id, 'end_time' => ['>', time()],'flag'=>0])->find();
                    $isUse = true;
                    if (!empty($red_packet_info['seller_id'])) {
                        $seller_id_array = explode(',', $red_packet_info['seller_id']);
                        if (!in_array($seller_id,$seller_id_array)) {
                            $isUse = false;
                        }
                    }
                    if ($isUse) {
                        if (!empty($red_packet_info['full'])) {
                            if ($red_packet_info['full'] > $isDis_price) {
                                $isUse = false;
                            }
                        }
                    }
                    if ($isUse) {
						$intime = explode('-',$red_packet_info['intime']);
                        if (!empty($intime)) {
                            if ( date('i') < $intime[0] || date('i') > $intime[1] ) {
                                $isUse = false;
                            }
                        }
                    }
                    if ($isUse) {
                        $data['red_packet'] = (string)$red_packet_info['minus'];
                    } else {
                        $data['red_packet'] = '';
                    }
                }
                $isDis_price -= $data['red_packet'];

                //最终价格
                $last_price = $isDis_price;
                if ($last_price <= 0) {
                    $last_price = 0.01;
                }
                $data['last_price'] = (string)$last_price;

                if (!empty($pay) && $msg['state'] == 1) {
                    //生成订单,拉取微信支付
                    $order = [];
                    $order['order_id'] = date('ymdHis') . rand(1111, 9999);
                    $seller_order_id = Db::table('order')->where(['seller_id' => $seller_id,'date'=>date("Y-m-d")])->order('seller_order_id desc')->value('seller_order_id');
                    $order['seller_order_id'] = (int)$seller_order_id + 1;
                    $order['seller_id'] = $seller_id;
                    $order['title'] = $seller['name'];
                    $order['uid'] = $uid;
                    $order['pid'] = $seller['pid'];
                    $order['cid'] = $seller['cid'];
                    $order['aid'] = $seller['aid'];
                    $order['phone'] = $data['address_obj']['phone'];
                    $order['name'] = $data['address_obj']['name'];
                    $order['address'] = $data['address_obj']['address_title'] . $data['address_obj']['address_content'] . $data['address_obj']['address_detail'];
                    $order['lng'] = $data['address_obj']['lng'];
                    $order['lat'] = $data['address_obj']['lat'];
                    $order['money_off'] = $data['money_off'];
                    $order['system_money_off'] = $system_minus;
                    $order['seller_money_off'] = $seller_minus;
                    $order['red_packet'] = $red_id;
                    $order['new_user_reduction'] = $data['new_user_reduction'];
                    $order['express_charge'] = $data['express_charge'];
                    $order['box_charge'] = $data['box_charge'];
                    $order['goods_price'] = $data['goods_price'];
                    $order['last_price'] = $data['last_price'];
                    $order['remark'] = (string)$remark;
                    $order['date'] = date("Y-m-d");
                    $order['instore'] = $instore;
                    $order['status'] = 1;
                    $order['time'] = time();
                    $order['sum_price'] = (string)$data['sum_price'];
                    $order['red_id'] = (int)$red_id;
                    $order['red_packet'] = (string)$data['red_packet'];
                    $order['money_off_text'] = (string)$data['money_off_text'];
                    if ($data['red_packet'] != '') {
                        Db::table('red_packet')->where('id', $order['red_packet'])->update(['flag' => 1]);
                    }
                    if($seller['business'] == 0){
                        $msg['state'] = 0;
                        $msg['msg'] = '商家休息中，无法接单';
                        if($seller['advance'] == 1){
                            $order['advance'] = 1;
                            $msg['state'] = 1;
                            $msg['msg'] = '商家休息中，您的订单会在商家营业后处理';
                            Db::table('order')->insert($order);

                            //商品
                            Db::table('cart')->where(['uid' => $uid, 'seller_id' => $seller_id, 'order_id' => ''])->delete();
                            foreach ($data['goods'] as $k => $v) {
                                Db::table('order_detail')->insert(['order_id' => $order['order_id'], 'seller_id' => $seller_id, 'goods_id' => $v['goods_id'], 'title' => $v['title'], 'image' => $v['image'], 'service' => $v['service'], 'number' => $v['number'], 'price' => $v['price'],'box_charge'=>$v['box_charge']]);
                            }

                            $msg['data'] = $this->wxpay($order);
                        }
                    }else{
                        Db::table('order')->insert($order);

                        //商品
                        Db::table('cart')->where(['uid' => $uid, 'seller_id' => $seller_id, 'order_id' => '', 'instore' => $instore])->update(['order_id' => $order['order_id']]);
                        foreach ($data['goods'] as $k => $v) {
                            Db::table('order_detail')->insert(['order_id' => $order['order_id'], 'seller_id' => $seller_id, 'goods_id' => $v['goods_id'], 'title' => $v['title'], 'image' => $v['image'], 'service' => $v['service'], 'number' => $v['number'], 'price' => $v['price'],'box_charge'=>$v['box_charge']]);
                        }

                        $msg['data'] = $this->wxpay($order);
                    }
                } else {
                    $msg['data'] = $data;
                }
            }
        }
        return json($msg);
    }

    //微信支付
    public function wxpay($data = null)
    {
        vendor('wxpayv_app.WxPay#Api');
        if (!$data) {
            $order_id = req('order_id');
            $data = Db::table('order')->where('order_id', $order_id)->find();
            // $new_id = date('ymdHis') . rand(1111, 9999);
            // Db::table('order')->where('order_id',$order_id)->update(['order_id'=>$new_id]);
            // Db::table('cart')->where('order_id',$order_id)->update(['order_id'=>$new_id]);
            // Db::table('order_detail')->where('order_id',$order_id)->update(['order_id'=>$new_id]);
            // $data['order_id'] = $new_id;
            $order_id = $data['order_id'];
        } else {
            $order_id = $data['order_id'];
        }
        $back_url = \think\Url::build('wxpayNotify', '', true, true);
        $unifiedOrder = new \WxPayUnifiedOrder();
        $unifiedOrder->SetBody('途骑外卖支付');
        $unifiedOrder->SetOut_trade_no($data['order_id']);
        $unifiedOrder->SetTotal_fee($data['last_price'] * 100);
        $unifiedOrder->SetNotify_url($back_url);
        $unifiedOrder->SetTrade_type('APP');
        $result = \WxPayApi::unifiedOrder($unifiedOrder);
        $result['order_id'] = $order_id;
        $result['price'] = $data['last_price'];
		if (req('order_id')) {
			$msg['state'] = 1;
			$msg['data'] = $result;
			$msg['msg'] = '获取成功';
			return json($msg);
        } else {
			return $result;
        }
    }

    public function pay_next()
    {
        $order_id = req('order_id');
        $pay_type = req('pay_type');
        $order = Db::table('order')->where('order_id', $order_id)->find();
        $msg['state'] = 0;
        $msg['data'] = '';
        if(empty($order_id)){
            $msg['msg'] = '参数错误';
        }else {
            $pay_status = false;
            if ($pay_type == 'alipay') {
                $this->alipay_config = db("payment")->find();
                vendor('alipay.AopSdk');
                $aop = new \AopClient ();
                $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
                $aop->appId = $this->alipay_config['app_id'];
                $aop->rsaPrivateKey = $this->alipay_config['privatekey'];
                $aop->alipayrsaPublicKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI6d306Q8fIfCOaTXyiUeJHkrIvYISRcc73s3vF1ZT7XN8RNPwJxo8pWaJMmvyTn9N4HQ632qJBVHf8sxHi/fEsraprwCtzvzQETrNRwVxLO5jVmRGi60j8Ue1efIlzPXV9je9mkjzOmdssymZkh2QhUrCmZYI/FCEa3/cNMW0QIDAQAB';
                $aop->apiVersion = '1.0';
                $aop->signType = 'RSA';
                $aop->postCharset = 'utf-8';
                $aop->format = 'json';
                vendor('alipay.aop.request.AlipayTradeQueryRequest');
                $request = new \AlipayTradeQueryRequest ();
                $request->setBizContent("{" .
                    "    \"out_trade_no\":\"" . $order_id . "\"," .
                    "    \"trade_no\":\"\"" .
                    "  }");
                $result = $aop->execute($request);
                $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
                $resultCode = $result->$responseNode->code;
                if (!empty($resultCode) && $resultCode == 10000) {
                    $order = Db::table('order')->where('order_id', $order_id)->find();
                    if ($result->$responseNode->trade_status == "TRADE_SUCCESS" && $result->$responseNode->total_amount == $order['last_price']) {
                        $pay_status = true;
                        //push商家通知,
                        $msg['msg'] = '支付成功';
                    } else {
                        $msg['msg'] = '支付失败';
                    }
                } else {
                    $msg['msg'] = '支付失败';
                }
            } elseif ($pay_type == 'wxpay') {
                vendor('wxpayv_app.WxPay#Api');
                $input = new \WxPayOrderQuery();
                $input->SetOut_trade_no($order_id);
                $result = \WxPayApi::orderQuery($input);

                if ($result['result_code'] == "SUCCESS") {
                    if ($result['trade_state'] == "SUCCESS" && $result['total_fee'] == (string)($order['last_price'] * 100)) {
                        $pay_status = true;
                        //push商家通知,
                        $msg['msg'] = '支付成功';
                    } else {
                        $msg['msg'] = '支付失败';
                    }
                }
            }

            // $pay_status = true;
            // $msg['state'] = 1;
            // $msg['msg'] = '支付成功';

            //支付成功，给商家加钱是不可以的，必须订单完成才可以
            if ($pay_status) {
                $msg['state'] = 1;
                Db::table('order')->where('order_id', $order_id)->update(['status' => 2, 'payment' => $pay_type, 'pay_time' => time()]);

                $seller = Db::table('seller')->where('id', $order['seller_id'])->find();
                if ($seller['business'] == 1) {
					push(md5($order['seller_id']), json_encode(['type' => 4, 'message' => '您有新的订单赶快接单吧~', 'parameters' => $order_id]), 'seller');
                    insert_message('seller', $order['seller_id'], '订单提醒', '您有新的订单赶快接单吧~', '4', $order_id);
                }
            }
        }
        return json($msg);
    }

}